﻿/**
 * Created in 2012-2-21.
 */
package kit4j.common.io;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

/**
 * 
 * @author MiniKnife
 *
 */
public class TxtExtractor {

	/**
	 * 从给定的输入流中读取字符串。
	 * @param in 输入流
	 * @return 从输入流中读取到的字符串。
	 * @throws IOException
	 */
	public static String getText(InputStream in) throws IOException {
		Charset charset = getTxtStreamCharset(in);
		InputStreamReader reader = new InputStreamReader(in, charset);
		char[] charBuf = new char[1024];
		StringBuffer strBuf = new StringBuffer();
		int readLength;

		while ((readLength = reader.read(charBuf, 0, charBuf.length)) != -1) {
			strBuf.append(charBuf, 0, readLength);
		}

		return strBuf.toString();
	}

	/**
	 * 获取给定输入流的编码字符集。
	 * @param in 输入流
	 * @return 字符集。
	 */
	public static Charset getTxtStreamCharset(InputStream in) {
		if(!in.markSupported()) {
			in = new BufferedInputStream(in);
		}
		
		// 读取输入流的前3个字节判断输入流的编码戳
		int headLength = 3;
		byte[] streamHead = new byte[headLength];
		Charset charset = null;

		try {
			in.mark(headLength);
			in.read(streamHead);
			in.reset();
		} catch (IOException e) {
			e.printStackTrace();
		}

		if (streamHead[0] == (byte) 0xFF && streamHead[1] == (byte) 0xFE) {
			charset = Charset.forName("UTF-16");
		} else if (streamHead[0] == (byte) 0xFE && streamHead[1] == (byte) 0xFF) {
			charset = Charset.forName("UTF-16BE");
		} else if (streamHead[0] == (byte) 0xEF && streamHead[1] == (byte) 0xBB
				&& streamHead[2] == (byte) 0xBF) {
			charset = Charset.forName("UTF-8");
		} else {
			charset = Charset.forName("GB2312");
		}

		return charset;
	}
}
